<template>
  <div class="main-page" id="myDiv">
    <div class="main-cards">
      <div v-for="(card, index) in bluetoothCards" :key="card.id" class="main-card" @click="handleConnect(index)">
        <div class="device-info">
          <div class="battery-top-right">
            <div class="battery-container">
              <span class="battery-text">{{ card.deviceName + '电量' + card.batteryLevel }}%</span>
            </div>
            <div>{{ card.breakMsg }}</div>
          </div>

          <!-- 疲劳指标 -->
          <div class="device-battery">
            <div class="data-item">
              <span>疲劳指标</span>
              <div class="progress-bg">
                <div class="progress-fill" :style="{ width: card.pilaoValue + '%' }"></div>
              </div>
              <span class="progress-value">{{ card.pilaoValue }}</span>
            </div>
          </div>

          <!-- 专注 -->
          <div class="device-battery">
            <div class="data-item">
              <span>专注指标</span>
              <div class="progress-bg">
                <div class="progress-fill" :style="{ width: card.zhuanzhuValue + '%' }"></div>
              </div>
              <span class="progress-value">{{ card.zhuanzhuValue }}</span>
            </div>
          </div>

          <!-- 睡意 -->
          <div class="device-battery">
            <div class="data-item">
              <span>睡意指标</span>
              <span class="progress-value" v-if="card.shuiyiValue == 1">浅睡期</span>
              <span class="progress-value" v-if="card.shuiyiValue == 2">眼动期</span>
              <span class="progress-value" v-if="card.shuiyiValue == 3">清醒期</span>
              <span class="progress-value" v-if="card.shuiyiValue == 4">清醒期</span>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BluetoothManager from '@/bluetooth.js';

import { EEGFatigueCalculator } from '@/eegFatigueCalculator';
import { AttentionScoreMain } from '@/EEGAttentionScore';
import { SleepStageServeMain } from '@/EEGSleepStageScore';

const bluetooth = new BluetoothManager();
const nameArr = ["ML_2_Lead_2328", "ML_2_Lead_0F3F", "ML_2_Lead_0F41", "ML_2L_SAFE"]
export default {
  data() {
    return {
      nameArr,
      bluetoothCards: Array.from({ length: 4 }, (_, index) => ({
        id: index + 1,
        deviceName: nameArr[index], // 生成唯一设备名（0001-0004）
        isConnected: false,
        batteryLevel: 0,
        breakMsg: '未连接',

        pilao: new EEGFatigueCalculator(),
        zhuanzhu: new AttentionScoreMain(),
        shuiyi: new SleepStageServeMain(),

        pilaoValue: 0,
        zhuanzhuValue: 0,
        shuiyiValue: 0,
      }))
    };
  },

  methods: {
    async handleConnect(index) {
      console.log('handleConnect');
      const card = this.bluetoothCards[index];
      if (card.isConnected) {
        await bluetooth.disconnect(index);
        card.isConnected = false;
        card.breakMsg = '已断开';
        return;
      }

      const connected = await bluetooth.initBle(
        index,
        '6e400001-b5a3-f393-e0a9-e50e24dcca9e',
        '6e400002-b5a3-f393-e0a9-e50e24dcca9e',
        '6e400003-b5a3-f393-e0a9-e50e24dcca9e',
        card.deviceName // 使用卡片自身的设备名
      );

      if (connected) {
        card.isConnected = true;
        this.startDataListening(index);
        card.breakMsg = '已连接';
        // await bluetooth.sendData(index, new Uint8Array([0xAA, 0xCC, 0x06, 0x03, 0x00, 0x55]));
        console.log(`卡片 ${index + 1} 连接成功：${card.deviceName}`);
      } else {
        card.breakMsg = '连接失败';
      }
    },

    startDataListening(index) {
      bluetooth.setCallbacks(
        index,
        (data, idx) => this.handleDataReceive(data, idx),
        () => this.handleDisconnect()
      );
    },
    handleDisconnect() { },

    handleDataReceive(data, index) {
      const card = this.bluetoothCards[index];
      const hexString = this.arrayBufferToHexString(data.buffer).toLowerCase();
      const now = Date.now();

      if (now - card.lastUpdateTime < 20) return;
      card.lastUpdateTime = now;

      this.parse2LeadData(card, hexString, index);
    },

    // 解析2Lead设备数据（仅EEG）
    parse2LeadData(card, hexString, index) {
      try {
        // 解析电量
        card.batteryLevel = parseInt(hexString.substring(2, 4), 16);
        // 解析EEG数据
        let brainwave = this.hexToFloat(hexString.substring(24, 32)) * Math.pow(10, 6);
        let brainwave1 = 200 - parseInt(Math.random() * 400)
        // 更新心理疲劳
        let temp1 = card.pilao.addDataPoint(brainwave)
        let temp2 = card.zhuanzhu.calculateAttentionScore(brainwave1)
        let temp3 = card.shuiyi.outPutSleepStage(brainwave)

        // console.log(index, temp1, temp2, temp3);
        // console.log(index, brainwave);

        if (temp1 != -1) {
          temp1 = parseInt(temp1)
          card.pilaoValue = Math.max(0, temp1)
        }
        if (temp2 != -1) {
          temp2 = parseInt(temp2)
          card.zhuanzhuValue = Math.max(0, temp2)
        }
        if (temp3 != -1) {
          temp3 = parseInt(temp3)
          card.shuiyiValue = Math.max(0, temp3)
        }


      } catch (error) {
        console.error(`卡片 ${card.id} 解析2Lead数据失败：`, error);
      }
    },


    // 二进制转浮点数（保留原有方法）
    hexToFloat(hexString) {
      const hex = parseInt(hexString, 16);
      const sign = (hex >> 31) ? -1 : 1;
      const exponent = ((hex >> 23) & 0xFF) - 127;
      const mantissa = (hex & 0x7FFFFF) / Math.pow(2, 23);
      return sign * (1 + mantissa) * Math.pow(2, exponent);
    },

    // 数组缓冲区转十六进制字符串（保留原有方法）
    arrayBufferToHexString(buffer) {
      return [...new Uint8Array(buffer)]
        .map(b => b.toString(16).padStart(2, '0'))
        .join('');
    }
  },

  beforeDestroy() {
    this.bluetoothCards.forEach((_, index) => bluetooth.disconnect(index));
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.main-page {
  min-height: 100vh;
  padding: 30px;
  background-color: #3c8cdb;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-image: url('~@/../public/piano-bg.jpg');
  background-size: cover;
  background-position: center;
}

.main-title {
  text-align: center;
  font-size: 28px;
  margin-top: 30px;
  margin-bottom: 40px;
  font-weight: 600;
  color: hsl(106, 72%, 46%);
}

.main-cards {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 30px;
  max-width: 1800px;
  width: 100%;
  margin: 120px auto;
  overflow-x: auto;
}

.main-card {
  width: 320px;
  height: 250px;
  background: white;
  border-radius: 18px;
  padding: 30px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease;
}

.main-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.main-card:active {
  transform: translateY(1px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.battery-top-right {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 25px;
}

.device-info {
  width: 100%;
}

.battery-container {
  display: flex;
  align-items: center;
}

.battery-text {
  margin-right: 8px;
  font-size: 14px;
  color: #666;
}

.device-battery {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  width: 100%;
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.data-item span:first-child {
  font-size: 16px;
  color: #555;
  min-width: 75px;
}

.progress-bg {
  flex: 1;
  height: 12px;
  background-color: #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  margin: 0 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 6px;
  transition: width 0.5s ease;
}

.progress-value {
  min-width: 35px;
  text-align: right;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

/* 睡眠阶段样式 */
.sleep-stage-info {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.sleep-label {
  font-size: 16px;
  color: #555;
  margin-right: 10px;
}

.sleep-value {
  font-size: 16px;
  font-weight: 500;
}

.sleep-deep {
  color: #2e7d32;
}

/* 深睡：绿色 */
.sleep-light {
  color: #f57c00;
}

/* 浅睡：橙色 */
.sleep-rem {
  color: #1976d2;
}

/* REM：蓝色 */
.sleep-awake {
  color: #d32f2f;
}

/* 清醒：红色 */
.sleep-unknown {
  color: #666;
}

/* 未知：灰色 */

@media (max-width: 1200px) {
  .main-cards {
    max-width: 900px;
  }

  .main-card {
    width: 280px;
    padding: 25px;
  }
}

@media (max-width: 768px) {
  .main-page {
    padding: 20px;
  }

  .main-title {
    font-size: 24px;
    margin-bottom: 30px;
  }

  .main-cards {
    flex-direction: column;
    gap: 25px;
  }
}
</style>